package com.swt.agy.backend.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.util.UUID;

/**
 * @Auther: yxd
 * @Date: 2019/4/10 16:46
 * @Description: 文件工具类，主要用于处理文件上传下载
 * @Version: V1.0
 */
public class FileUtils {

    /**
     * 文件下载
     * @param response
     * @param file
     * @param fileName
     * @return
     */
    public static ResponseEntity download(HttpServletResponse response, File file, String fileName) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            response.setCharacterEncoding("UTF-8");
            byte[] buffer = new byte[1024];
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            return ResponseEntity.ok("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("下载失败");
    }

    /**
     * 返回值为文件存放路径
     * @param file
     * @param uploadPath
     * @return
     * @throws IOException
     */
    public static String upload(MultipartFile file, String uploadPath) throws IOException {
        String fileName = file.getOriginalFilename();
        String attachmentName = UUID.randomUUID().toString().replaceAll("-", "") + "_" + file.getOriginalFilename();
        File parentPath = new File(uploadPath);
        if(!parentPath.exists()) {
            parentPath.mkdirs();
        }
        String fullPath = uploadPath + File.separator + attachmentName;
        File dest = new File(fullPath);
        file.transferTo(dest);
        return attachmentName;
    }

    /**
     * SpringMVC的文件接收类转换成JAVA中的File类
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile multipartFile) throws Exception{
        File toFile = null;
        if(multipartFile.equals("")||multipartFile.getSize()<=0){
            multipartFile = null;
        }else {
            InputStream ins = null;
            ins = multipartFile.getInputStream();
            toFile = new File(multipartFile.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    /**
     * File转换成MultipartFile
     * @param file
     * @return
     * @throws Exception
     */
    public static MultipartFile fileToMultipartFile(File file) throws Exception {
        FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false,
                file.getName(), (int) file.length(), file.getParentFile());
        InputStream is = new FileInputStream(file);
        OutputStream os = fileItem.getOutputStream();
        IOUtils.copy(is, os);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        os.close();
        is.close();
        return multipartFile;
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除项目目录下的临时文件
     * @param file
     */
    public static void deleteFile(File file) {
        File del = new File(file.toURI());
        del.delete();
    }
}
